package com.callback.confirmreturndemo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 设置两个callback的方式二
 */
@Slf4j
@RestController
public class CallBackSendMessage {
    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostConstruct //构造方法后执行它，相当于初始化作用
    public void init(){
        rabbitTemplate.setConfirmCallback(
                //匿名内部类
                new RabbitTemplate.ConfirmCallback() {
                    @Override
                    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                        log.info("关联id为：{}",correlationData.getId()+"");
                        if (ack){
                            log.info("消息正确的达到交换机");
                            return;
                        }
                        //ack =false 没有到达交换机
                        log.error("消息没有到达交换机，原因为：{}",cause);
                    }
                }
        );
        rabbitTemplate.setReturnCallback(
                new RabbitTemplate.ReturnCallback() {
                    @Override
                    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                        log.error("消息未送达oqueue message:{},replyCode:{},replyText:{},exchange:{},routingKey:{}",
                                message.getBody(),
                                replyCode,
                                replyText,
                                exchange,
                                routingKey);

                    }
                }
        );
    }

}
